# coding=utf-8
import json

from flask.blueprints import Blueprint
from flask import request, render_template

from src.api.response.R import R
from src.db.dbhelper import query_sql_by_pandas

data_api = Blueprint('data_api', __name__, url_prefix="/api/data")


@data_api.route("/data_manager_page", methods=["GET"])
def data_manager_page():
    sql = "select id, plan_name from material_plan where is_del = 0 and is_finish = 2 "
    df = query_sql_by_pandas(sql)
    plan_dic = dict(zip(df["id"], df["plan_name"]))
    return render_template("/data/data_manager_page.html", plan_dic=plan_dic)


@data_api.route("/get_material_use_pert", methods=["POST"])
def get_material_use_pert():
    plan_id = request.form.get("plan_id")
    r = R()
    if plan_id is None or plan_id == "":
        r.code = 500
        r.msg = "请先选择执行计划"
        return r.to_dict()
    sql = f"select plan_name, remark_type, remark from material_plan_other where plan_id = {plan_id} "
    # material_type_df = query_sql_by_pandas(f"select id, name from material_type where is_del = 0 ")
    # material_type_dic = dict(zip(material_type_df["id"], material_type_df["name"]))
    source_df = query_sql_by_pandas(sql)
    if source_df.empty:
        r.code = 500
        r.msg = "无数据"
        return r.to_dict()
    # ["剩余物料", "已使用物料", "物料总量"]
    source_dic_df = source_df[source_df["remark_type"] == "总量"]
    if source_dic_df.empty:
        r.code = 500
        r.msg = "无数据"
        return r.to_dict()
    source_remark = source_dic_df.iloc[0]["remark"]
    source_remark_dic = json.loads(source_remark)

    remain_dic_df = source_df[source_df["remark_type"] == "剩余"]
    if remain_dic_df.empty:
        r.code = 500
        r.msg = "无数据"
        return r.to_dict()
    remain_remark = remain_dic_df.iloc[0]["remark"]
    remain_remark_dic = json.loads(remain_remark)

    use_dic_df = source_df[source_df["remark_type"] == "已使用"]
    if use_dic_df.empty:
        r.code = 500
        r.msg = "无数据"
        return r.to_dict()
    use_remark = use_dic_df.iloc[0]["remark"]
    use_remark_dic = json.loads(use_remark)

    result_dic = {

    }
    tags = []
    source = []
    use = []
    remain = []
    percentages = []
    for key, val in source_remark_dic.items():
        # tag = material_type_dic.get(key)
        tags.append(key)
        source.append(val)
        use_val = use_remark_dic.get(key)
        use.append(use_val)
        remain_val = remain_remark_dic.get(key)
        remain.append(remain_val)
        if float(val) == 0:
            percentage = 0
        else:
            percentage = (float(use_val)/float(val)) * 100
        percentages.append(percentage)
    r.data = {"tags": tags, "source": source, "use": use, "remain": remain, "percentages": percentages}
    r.code = 200
    return r.to_dict()
